<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 店铺名称管理
 *
 * @icon fa fa-circle-o
 */
class Feditionaccounturl extends Backend
{
    
    /**
     * Feditionaccounturl模型对象
     * @var \app\admin\model\Feditionaccounturl
     */
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Feditionaccounturl;
        $this->view->assign("statusList", $this->model->getStatusList());

        $accountpay = $this->request->param('accountpay');
        $this->assignconfig('accountpay', $accountpay);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where2 = array();
            $accountpay = $this->request->param('accountpay');
            if($accountpay >0){
                $account = Db::name('fedition_websitepaytype')
                        ->field("b.account_address")
                        ->alias('a')
                        ->join('fa_fedition_website b', 'b.id = a.website_id and b.account_address = a.accounturl_id', 'left')
                        ->where('a.accountpay_id','=',$accountpay)
                        ->where('b.account_address','exp','is not null')
                        ->select();
                $newaccount = array();
                if (!empty($account)) {
                    foreach ($account as $item) {
                        $newaccount[] = $item['account_address'];
                    }
                }
                $where2['id'] = array('in',$newaccount);
            }
            
            $list = $this->model
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){

                    $ordershoplaza = array();
                    
                    $wheregroup['accounturl'] = $v['id'];
                    $wheregroup['createtime'] = array('elt',time());
                    $wheregroup['updatetime'] = array('egt',time());
                    $accounturlgroup = Db::name('fedition_accounturlgroup')->where($wheregroup)->find();
                    if(!empty($accounturlgroup)){

                        $admin = Db::name('admin')->where('id', '=', $accounturlgroup['admin_id'])->find();
                        if($admin){
                            $lists[$k]['admin_name'] = $admin['nickname'];
                        }else{
                            $lists[$k]['admin_name'] = '用户已删除';
                        }
                        $lists[$k]['admin_name'] = $admin['nickname'];
                    }else{
                        $lists[$k]['admin_name'] = '没有归属';
                    }

                    if ($v['iscustom'] == 1) {
                        $ordershopify = Db::name('fedition_ordershopify')
                            ->where('accounturl', $v['id'])
                            ->order('updated_at desc')
                            ->find();
                        $ordershopifycount1 = Db::name('fedition_ordershopify')
                            ->where('accounturl', $v['id'])
                            ->where('financial_status', 'paid')
                            ->count();
                        $ordershopifycount2 = Db::name('fedition_ordershopify')
                            ->where('accounturl', $v['id'])
                            ->where('fulfillment_status', 'fulfilled')
                            ->count();
                        $ordershopifycount3 = Db::name('fedition_ordershopify')
                            ->where('accounturl', $v['id'])
                            ->where('financial_status', 'refunded')
                            ->count();
                        $ordershopifycount4 = Db::name('fedition_ordershopify')
                            ->where('accounturl', $v['id'])
                            ->where('financial_status', 'partially_refunded')
                            ->count();
                        $lists[$k]['ordershoplazacount'] = array($ordershopifycount1,$ordershopifycount2,$ordershopifycount3,$ordershopifycount4);
                        if (!empty($ordershopify)) {
                            $lists[$k]['ordershoplaza_time'] = $ordershopify['updated_at'];
                        } else {
                            $lists[$k]['ordershoplaza_time'] = '';
                        }
                    } elseif($v['iscustom_shoplaza'] == 1) {
                        $ordershoplaza = Db::name('fedition_ordershoplaza')
                            ->where('accounturl', $v['id'])
                            ->order('updated_at desc')
                            ->find();
                        $ordershoplazacount1 = Db::name('fedition_ordershoplaza')
                            ->where('accounturl', $v['id'])
                            ->where('financial_status', 'paid')
                            ->count();
                        $ordershoplazacount2 = Db::name('fedition_ordershoplaza')
                            ->where('accounturl', $v['id'])
                            ->where('fulfillment_status', 'finished')
                            ->count();
                        $ordershoplazacount3 = Db::name('fedition_ordershoplaza')
                            ->where('accounturl', $v['id'])
                            ->where('order_status', 'cancelled')
                            ->count();
                        $ordershoplazacount4 = 0;
                        $lists[$k]['ordershoplazacount'] = array($ordershoplazacount1,$ordershoplazacount2,$ordershoplazacount3,$ordershoplazacount4);
                        if (!empty($ordershoplaza)) {
                            $lists[$k]['ordershoplaza_time'] = $ordershoplaza['updated_at'];
                        } else {
                            $lists[$k]['ordershoplaza_time'] = '';
                        }
                    }else{
                        $lists[$k]['ordershoplazacount'] = [0,0,0];
                        $lists[$k]['ordershoplaza_time'] = '';
                    }
                }
            }
            $Statistics = array();
            $Statistics['zcountnum'] = $this->model
                ->count();
            $Statistics['shopifysum1'] = $this->model
                ->where('iscustom',1)
                ->where('status','normal')
                ->count();
            $Statistics['shopifysum2'] = $this->model
                ->where('iscustom',1)
                ->where('status','unavailable')
                ->count();
            $Statistics['shoplaza1'] = $this->model
                ->where('iscustom_shoplaza',1)
                ->where('status','normal')
                ->count();
            $Statistics['shoplaza2'] = $this->model
                ->where('iscustom_shoplaza',1)
                ->where('status','unavailable')
                ->count();
            $result = array("total" => $list->total(), "rows" => $lists, "Statistics" => $Statistics);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //判断是否有http://
                    if (!preg_match('/(http:\/\/)|(https:\/\/)/i', $params['url'])) {
                        $this->error(__('请输入http或https'));
                    }
                    $params['admin_id'] = $this->auth->id;
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}
